package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Map;

    public class Config {
        private final int port = 8080;
        private final String webRoot = "webroot";
        private final Map<String, Handler> handlerMap = new HashMap<>();

        private Config() {
            handlerMap.put("/", new DefaultHandler());
            handlerMap.put("/time", new TimeHandler());
            handlerMap.put("/echo", new EchoHandler());
        }

        public static Config getInstance() {
            return Holder.INSTANCE;
        }

        private static class Holder {
            private static final Config INSTANCE = new Config();
        }

        public int getPort() {
            return port;
        }

        public String getWebRoot() {
            return webRoot;
        }

        public Handler getHandler(String url) {
            // TODO: [222024321072035/万能] 实现 URL 精确匹配或基础路径匹配逻辑
            if (handlerMap.containsKey(url)) {
                return handlerMap.get(url);
            }

            // 2. 尝试匹配父路径（如/static/* 匹配/static）
            String[] segments = url.split("/");
            for (int i = segments.length - 1; i > 0; i--) {
                StringBuilder path = new StringBuilder();
                for (int j = 1; j <= i; j++) {
                    path.append("/").append(segments[j]);
                }
                String parentPath = path.toString();
                if (handlerMap.containsKey(parentPath)) {
                    return handlerMap.get(parentPath);
                }
            }
            return null;
        }
    }


